<template>
	<gracePage :customHeader="false">
		<view slot="gBody" class="grace-body">
		<form @submit="formSubmit" class="grace-form grace-margin-top">
			<view class="grace-form-item grace-border-b">
				<text class="grace-icons icon-scancode grace-form-icon grace-blue"></text>
				<text class="grace-form-label">产品名称</text>
				<view class="grace-form-body">
					<view class="grace-form-input">{{object.field3}}</view>
				</view>
			</view>			
			<view class="grace-form-item grace-border-b">
				<text class="grace-icons icon-set grace-form-icon grace-blue"></text>
				<text class="grace-form-label">订单编码</text>
				<view class="grace-form-body">
					<view class="grace-form-input">{{object.field1}}</view>
				</view>
			</view>
			<view class="grace-form-item grace-border-b" style="display: none;">
				<text class="grace-icons icon-time grace-form-icon grace-blue"></text>
				<text class="grace-form-label">创建时间</text>
				<view class="grace-form-body">
					<view class="grace-form-input">{{object.createTime}}</view>
				</view>
			</view>	
			<view class="grace-form-item grace-border-b">
				<text class="grace-icons icon-wallet grace-form-icon grace-blue"></text>
				<text class="grace-form-label">订单金额</text>
				<view class="grace-form-body">
					<view class="grace-form-input">￥{{object.field13}}元</view>
				</view>
			</view>	
			<view class="grace-form-item grace-border-b">
				<text class="grace-icons icon-help1 grace-form-icon grace-blue"></text>
				<text class="grace-form-label">订单状态</text>
				<view class="grace-form-body">
					<view class="grace-form-input">{{state}}</view>
				</view>
			</view>	
				
			<view v-if="orderHandleButton" class="demo">
				<view>
					<button @tap="cancel" type="primary" class="grace-button grace-bg-green">取消订单</button>
				</view>
				<view>
					<button formType="submit" type="primary" class="grace-button  grace-bg-blue" :disabled="formSubmitEnable">继续付款</button>
				</view>
			</view>																				
		</form>	
		</view>
	</gracePage>
</template>
<script>
import gracePage from "../../graceUI/components/gracePage.vue";
var _self;
export default {
    data() {
        return {
			object : {},
			state:"",
			objectUserPhone:"",
			onShareTimelineImageUrl:"",
			token:"",
			appInfo:"",
			id:"",//课程ID
			imageNum:false,
			userInfoData : "",
			pageNum : 1,
			//每次加载的记录数
			pageSize : 10,
			productionOrderBuyButton : "购买课程",
			productionOrderState:false	,
			formSubmitEnable:false,
			orderHandleButton:false
        }
    },
	onLoad: async function (e){
		_self = this;
		_self.$myFunction.displayLog("onLoad事件e:"+JSON.stringify(e));
		_self.id = e.id;
		//获取token，同步方法
		_self.token =  await _self.$myFunction.getToken();
		_self.token = _self.token.token;
		// 获取详情
		_self.getObjectDetail();
	},
    methods:{
		getObjectDetail: function(){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			var params = {
				'id': _self.id
			};	
			var paramsData = {
				"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
			}		
			//重
			//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
			_self.token = _self.$myFunction.appStorage('wuLuToken').token;				
			uni.request({
				url:  _self.$myFunction.appConfig().serverAddress+'productionOrderDetail',
				data: paramsData,
				method : "POST",
				header : {
					'content-type':'application/x-www-form-urlencoded',
					'Authentication':_self.token
				},					
				success: data => {
					uni.hideToast();
					_self.$myFunction.displayLog("服务器返回数据："+JSON.stringify(data));
					if (data.data.code == 200) {
						_self.object = data.data.data.productionOrderDto;
						if(_self.object.field15 == 'creating'){
							_self.state = "待付款";
							_self.orderHandleButton = true;
						}else if(_self.object.field15 == 'paySuccess'){
							_self.state = "使用中";
						}else if(_self.object.field15 == 'cancel'){
							_self.state = "已取消";
						}else if(_self.object.field15 == 'finish'){
							_self.state = "已完成";
						}
					}else{
						//如果请求数据因token认证失败，则清空缓存token
						if(data.data.message.indexOf("接口访问未认证") != -1){
							uni.setStorage({
								key: 'wuLuToken',
								data: "",
								success: function () {	
									_self.$myFunction.displayLog("清空缓存token");
									//触发重新获取token
									_self.$myFunction.getToken();
									// 关闭所有页面，打开到应用内的某个页面。
									_self.$myFunction.displayLog("重加载当前页面");
									uni.reLaunch({
										url: '/pages/object/detail'
									});
								}
							});
						}else{
							uni.showToast({title: "发生错误，请重试",icon: 'none'});
						}	
					}
				},
				fail: (data, code) => {
					uni.hideToast();
					uni.showToast({title: '连接失败...',icon: 'none'});
				}					
			});				
		},
		cancel: function(){
			// 选择确认
			uni.showModal({
				title: '提示',
				content: '确定取消该订单？',
				success: function (res) {
					if (res.confirm) {
						var params = {
							"id":_self.id,
							"field1":_self.object.field1,//订单编码
							"field2":_self.object.field2,//产品编码
							"field3":_self.object.field3,//产品名称
							"field4":_self.object.field4,//用户信息,支付成功后回调设置为openId
							"field5":_self.object.field5,//快递名称
							"field6":_self.object.field6,//快递单号
							"field7":_self.object.field7,//收货地址
							"field8":_self.object.field8,//收货姓名
							"field9":_self.object.field9,//收货手机
							"field10":_self.object.field10,//快递费用
							"field11":_self.object.field11,//订单数量
							"field12":_self.object.field12,//订单单价
							"field13":_self.object.field13,//订单金额
							"field14":_self.object.field14,//优惠金额
							"field15":"cancel",//订单状态
							"field16":_self.object.field16,//支付方式
							"field17":_self.object.field17,//订单信息
							"field18":_self.object.field18,//下单用户
							"field19":_self.object.field19,//订单备注
							"field20":_self.object.field20,//其它数据
							"status":1
						};
						var paramsData = {
							"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
						}
						//重新获取一次token，防止接口返回认证失败系统重新获取的token未被使用
						_self.token = _self.$myFunction.appStorage('wuLuToken').token;
						uni.request({
							url: _self.$myFunction.appConfig().serverAddress + 'productionOrderUpdate',
							data: paramsData,
							method: "POST",
							header: {
								'content-type': 'application/x-www-form-urlencoded',
								'Authentication': _self.token
							},
							success: data => {
								_self.$myFunction.displayLog("productionOrderUpdate服务器返回数据：" + JSON.stringify(data));
								let toastTitle, toastIcon, resType;
								if (data.data.code == 200) {
									_self.$myFunction.displayLog("订单取消成功" );
									uni.reLaunch({
										url: '/pages/order/index'
									});						
								}else{
									//如果请求数据因token认证失败，则清空缓存token
									if(data.data.message.indexOf("接口访问未认证") != -1){
										uni.setStorage({
											key: 'wuLuToken',
											data: "",
											success: function () {	
												_self.$myFunction.displayLog("清空缓存token");
												//触发重新获取token
												_self.$myFunction.getToken();
												// 关闭所有页面，打开到应用内的某个页面。
												_self.$myFunction.displayLog("重加载当前页面");
												uni.reLaunch({
													url: '/pages/order/add'	
												});
											}
										});
									}else{
										_self.$myFunction.displayLog("productionOrderCreate失败："+JSON.stringify(data));
										uni.hideToast();
										uni.showToast({title: '连接失败...',icon: 'none'});
									}	
								};
							},
							fail: (data, code) => {
								uni.hideToast();
								uni.showToast({title: '连接失败...',icon: 'none'});
							}
						});	
					} else if (res.cancel) {
						return;
					}
				}
			});	
		},
		//继续付款
		formSubmit : function(){
			let payUrl = _self.$myFunction.appConfig().serverIp + 'wechat/miniPay';
			_self.formSubmitEnable = true;
			_self.wxPay(payUrl, "油箱卫士", "油箱卫士", _self.object.field1, _self.object.field13, "ty.hnztgckj.com" ,"ty.hnztgckj.com");
		},
		wxPay:function(payUrl,body,attach,orderCode,total,notify_url,paySuccessUrl){
			uni.showToast({
				title: '请稍后...',
				duration:_self.$myFunction.appConfig().requestWaitTime,
				icon: 'none',
			});
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					//根据code从服务器换取openid
					_self.formSubmitEnable = true;
					uni.request({
						url: _self.$myFunction.appConfig().serverIp +'wechat/getWxMiniOpenid/' + loginRes.code,
						method: "GET",
						success: data => {
							_self.$myFunction.displayLog("根据code从服务器换取openid返回数据：" + JSON.stringify(data));
							//根据code从服务器换取openid返回数据：{"data":{"code":200,"data":"{\"session_key\":\"zh+khf2302b6Rn9F4Yw0Yw==\",\"openid\":\"o35XE5Kq_fr_5KhzhJSnxOPEHWoY\"}"},"header":{"Vary":"Origin,Access-Control-Request-Method,Access-Control-Request-Headers","Content-Type":"application/json","Transfer-Encoding":"chunked","Date":"Tue, 08 Aug 2023 07:36:11 GMT","Keep-Alive":"timeout=60","Connection":"keep-alive"},"statusCode":200,"cookies":[],"errMsg":"request:ok"}
							if (data.data.code == 200) {
								//利用获取到的openid、session_key和上一步骤获的encryptedData、iv解密
								_self.openId = JSON.parse(data.data.data).openid;
								
								let params = {
									'openid':_self.openId,
									'description' : body,
									'attach' : attach,
									'outTradeNo' : orderCode,
									'total' : total,
									'goodsTag' : "",
									'notifyUrl' : notify_url,
									//发送收货信息使用参数
									'orderExpressAddress' : "",
									'orderExpressReceiverName' : "",
									'orderExpressReceiverPhone' : "",
									'orderNum' : "",
									'orderPrice' : "",
									'orderAmount' : "",
									'openIdMerchant' : "",
									'paySuccessUrl' : paySuccessUrl
								};
								var paramsData = {
									"jsonParas":_self.$AesUtil.encrypt(encodeURIComponent(JSON.stringify(params)))
								}
								// 统一下单
								uni.request({
								  url: payUrl, 
								  data: paramsData,
								  method: 'GET',
								  header: {
								  	'content-type': 'application/x-www-form-urlencoded'
								  },
								  success: function (res) {
									  uni.hideToast();
									  _self.$myFunction.displayLog("统一下单：" + JSON.stringify(res));
									// 微信支付
									uni.requestPayment({
										timeStamp: res.data.data.timeStamp,
										nonceStr: res.data.data.nonceStr,
										package: res.data.data.packageVal,
										signType: res.data.data.signType,
										paySign: res.data.data.paySign,
										success: (res) => {
											uni.showToast({
												title: '支付成功',
												icon: 'success'
											});
											//清空购物车
											uni.$emit('orderListRefresh', {
												msg: '页面刷新'
											});
											setTimeout(function () {
												uni.redirectTo({
													url: '/pages/order/index'
												})							
											}, 1500)
										},
										fail: (res) => {
											_self.formSubmitEnable = false;
											uni.showModal({
												content: "支付失败",
												showCancel: false,
											});
										},
										complete: () => {
											// this.loading = false;
										}
									})	
								  },
									fail: (data, code) => {
										_self.formSubmitEnable = false;
										uni.showToast({title: '连接失败...',icon: 'none'});
									}
								})
							} else {
								_self.formSubmitEnable = false;
								uni.showToast({
									title: '服务器返回失败...',
									icon: 'none'
								});
							}
						},
						fail: (data, code) => {
							_self.formSubmitEnable = false;
							uni.showToast({
								title: '连接失败...',
								icon: 'none'
							});
						}
					});
				},
				fail: function(e) {
					_self.formSubmitEnable = false;
					uni.showToast({
						title: '微信授权登录失败',
						icon: 'none'
					});
				}
			});
		}
					
    },
	components: {
		gracePage
	}
}
</script>
<style>
	.grace-form-icon{font-size:40rpx;}
	.grace-form-label{width:170rpx;font-size:medium;}
	.grace-form-input{font-size:40rpx;text-align:left;margin:20rpx;}
	.grace-textarea.grace-form-input{height:240rpx !important;}
	.release-content{background:#EEEEEE;}	
	/* 按钮 */
	.demo{display:flex; flex-wrap:nowrap; border-left:1px solid #F8F8F8;}
	.demo view{width:100%; text-align:center; margin:10rpx;}
</style>